package com.example.a.controller;


import com.example.a.entity.OrderDetail;
import com.example.a.entity.OrderMaster;
import com.example.a.entity.PayUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;

import com.example.a.service.OrderDetailService;
import com.example.a.service.OrderMasterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

@Controller
@CrossOrigin(origins = "http://localhost:63342", allowCredentials = "true")
@RequestMapping("/api/alipay")
public class AliPayController {

    @Autowired
    private PayUtil payUtil;

    @Autowired
    private OrderMasterService orderManagementService;

    private OrderMaster order = null;
    private String tokens = "";

    @ResponseBody
    @PostMapping("/pay")
    public String alipay(@RequestHeader String token, @RequestParam("orderId") String orderId) {
        try {
            order = orderManagementService.findById(orderId);
            if (order == null) {
                return "订单信息不存在，请检查订单ID";
            }
            tokens = token;
            String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            String user = UUID.randomUUID().toString().replace("-", "").toUpperCase();
            String OrderNum = time + user;
            float oderValue = order.getOrderTotal().floatValue();
            System.out.println("商品名字是订单ID: " + order.getOrderId());

            // 直接返回支付宝页面HTML
            return payUtil.sendRequestToAlipay(OrderNum, oderValue, "订单ID: " + order.getOrderId());
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "支付宝接口调用失败，请稍后重试";
        }
    }

    // 当我们支付完成之后跳转这个请求并携带参数，我们将里面的订单id接收到，通过订单id查询订单信息，信息包括支付是否成功等
    @ResponseBody
    @GetMapping("/toSuccess")
    public String returns(String out_trade_no) throws ParseException {
        String query = payUtil.query(out_trade_no);
        System.out.println("==>" + query);
        JSONObject jsonObject = JSONObject.parseObject(query);
        Object o = jsonObject.get("alipay_trade_query_response");
        Map map = (Map) o;
        System.out.println(map);
        Object s = map.get("trade_status");
        // 支付完成后直接返回HTML跳转到前端订单页面
        return "<script>window.location.href='http://localhost:8081/orders';</script>";
    }
}